#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""  
@Project : project
@File : ip_val.py
@Author : 薄荷糖
@Time : 2025/9/9 18:06  
@脚本说明 : 
"""
import ipaddress
import threading
import warnings

from scapy.layers.l2 import ARP
from scapy.sendrecv import sr1

warnings.filterwarnings("ignore")
# 扫描单个 IP 是否存活（通过 ARP）
def arp_scan_ip(pdst="127.0.0.1", iface="VMware Virtual Ethernet Adapter for VMnet8"):
    try:
        # 构造 ARP 请求包
        send_pkg = ARP(pdst=pdst)
        # 发送 ARP 包，并等待响应（超时 0.1 秒）
        result_pkg = sr1(send_pkg, iface=iface, verbose=False, timeout=0.1)
        if result_pkg:
            psrc = result_pkg.sprintf("%ARP.psrc%")  # 目标 IP
            pmack = result_pkg.sprintf("%ARP.hwsrc%")  # 目标 MAC
            print(f"[+] {psrc} | {pmack} 存活")
    except Exception as e:
        pass
def run_ip(host, iface):
    try:
        # 尝试解析为单个 IP（如 192.168.1.1）
        ip_single = ipaddress.IPv4Address(host)
        print(f"[*] 开始扫描单个 IP: {ip_single}")
        arp_scan_ip(str(ip_single), iface)
    except ipaddress.AddressValueError:
        try:
            # 尝试解析为 CIDR 网段（如 192.168.1.0/24）
            network = ipaddress.IPv4Network(host, strict=False)
            print(f"[*] 开始扫描 IP 网段: {network}")
            threads = []
            for ip in network.hosts():  # 遍历该网段内的所有主机 IP
                ip_str = str(ip)
                t = threading.Thread(target=arp_scan_ip, args=(ip_str, iface))
                t.start()
                threads.append(t)
            for t in threads:
                t.join()
        except ipaddress.NetmaskValueError:
            print(f"[-] 错误的 IP 或 CIDR 格式: {host}，请使用如 192.168.1.1 或 192.168.1.0/24")
    except Exception as e:
        print(f"[-] 扫描过程中发生未知错误: {e}")